#include <iostream>
#include <vector>
#include <numeric>
#include <limits>
#include<algorithm>

using namespace std;

class Solution {
public:

	static bool cmp(const vector <int>&  v1, const vector <int>&  v2)
	{
		return v1[2] < v2[2];
	}
	vector < int > schedule(vector < vector < int > > arr) {
		for (int i = 0; i < arr.size(); i++)
		{
			arr[i].push_back(i);
		}
		sort(arr.begin(), arr.end(), cmp);
		vector<int> vin(arr.size(),-1);
		vector<int> maxv(arr.size(), 0);
		vector<vector<int>> res;
		res.push_back({ arr[0][3] });
		maxv[0] = arr[0][0];
		
		for (int i = 1; i < arr.size(); i++)
		{
			for (int j = i; j >= 0; j--)
			{
				if (arr[i][1]>=arr[j][2])
				{
					vin[i] = j;
					break;
				}
			}
			int temp = vin[i] == -1 ? arr[i][0] : maxv[vin[i]] + arr[i][0];
			maxv[i] = max(maxv[i - 1], temp);

			if (maxv[i] == maxv[i - 1])
			{
				res.push_back(res[i - 1]);
			}
			else
			{
				if (vin[i] == -1)
					res.push_back({ arr[i][3]});
				else{
					vector<int> tv(res[vin[i]]);
					tv.push_back(arr[i][3]);
					res.push_back(tv);
				}		
			}

		}
		cout << maxv[arr.size() - 1]<<endl;
		return res[arr.size()-1];
	}
};
int main() {
	vector < int > res;

	int arr_rows = 0;
	int arr_cols = 0;
	cin >> arr_rows >> arr_cols;
	vector< vector < int > > arr(arr_rows);
	for (int arr_i = 0; arr_i<arr_rows; arr_i++) {
		for (int arr_j = 0; arr_j<arr_cols; arr_j++) {
			int arr_tmp;
			cin >> arr_tmp;
			arr[arr_i].push_back(arr_tmp);
		}
	}
	Solution *s = new Solution();
	res = s->schedule(arr);
	for (int res_i = 0; res_i < res.size(); res_i++) {
		cout << res[res_i] << endl;;
	}

	return 0;

}
